package vip.indo.task.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.indo.task.common.MyRunnable;

import java.util.concurrent.ScheduledFuture;

/**
 * @author 田连印
 * @Date 2025/1/14 9:29
 * @Descripition
 */
@RestController
@RequestMapping("/quartz/task")
@Tag(name = "定时任务控制器")
@Import(ThreadPoolTaskScheduler.class)
public class TestTaskController {
    @Resource
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    private ScheduledFuture<?> future1;
    private ScheduledFuture<?> future2;


    @Operation(summary = "启动定时任务")
    @PostMapping("/startCron")
    public String startCron1() {
        future1 = threadPoolTaskScheduler.schedule(new MyRunnable(), triggerContext -> new CronTrigger("0/10 * * * * ?").nextExecutionTime(triggerContext).toInstant());
        System.out.println("定时任务正在执行");
        return "定时任务正在执行";
    }

    @PostMapping("/stopCron")
    @Operation(summary = "关闭定时任务")
    public String stopCron1() {
        if (future1 != null) {
            future1.cancel(true);
        }
        System.out.println("定时任务关闭");
        return "定时任务关闭成功！";
    }
}
